package com.howinfun.netty.handler;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.Method;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.howinfun.netty.pool.ClientChannelPool;
import com.howinfun.utils.JsonMapUtils;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Howinfun
 * @desc
 * @date 2019/10/22
 */
@Slf4j
public class WebSocketHandler extends ChannelInboundHandlerAdapter implements SocketListener{
    private String urlPfx = "http://127.0.0.1:8180/pay";
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //首次连接是FullHttpRequest
        if (null != msg && msg instanceof FullHttpRequest) {
            FullHttpRequest request = (FullHttpRequest) msg;
            String uri = request.uri();

            Map paramMap=getUrlParams(uri);
            //如果url包含参数，需要处理
            if(uri.contains("?")){
                String newUri=uri.substring(0,uri.indexOf("?"));
                System.out.println(newUri);
                request.setUri(newUri);
                ClientChannelPool.addChannel((String) paramMap.get("alipay_account_user_id"),ctx.channel());
            }
        }else if(msg instanceof TextWebSocketFrame){
            //正常的TEXT消息类型
            TextWebSocketFrame frame=(TextWebSocketFrame)msg;
            System.out.println("客户端收到服务器数据：" +frame.text());
            JSONObject jsonObject = JSON.parseObject(frame.text());
            String type = jsonObject.getString("type");
            JSONObject params = jsonObject.getJSONObject("params");

            handleMessage(type,jsonObject.getJSONObject("params"));
            if(type.equals("login")){
                if(null != params.getString("alipay_account_user_id")) {
                    ClientChannelPool.addChannel(params.getString("alipay_account_user_id"), ctx.channel());
                }
                JSONObject data = new JSONObject();
                data.put("type","login");
                data.put("code","success");
                ctx.channel().writeAndFlush(new TextWebSocketFrame(JSON.toJSONString(data)));
            }

        }
        super.channelRead(ctx, msg);
    }

    private void handleMessage(String type,JSONObject params){
        try {
            switch (type){
                case "login":
                    login(params);
                    break;
                case "alipayuserid":
                    alipayuserid(params);
                    break;
                case "notifyurl":
                    notifyurl(params);
                    break;
                case "uploadQrCode":
                    uploadQrCode(params);
                    break;
                case "getTransferNo":
                    getTransferNo(params);
                    break;
                default:
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void login(JSONObject jsonObject)throws Exception {


        Map<String, Object> paramsMap = JsonMapUtils.json2map(JSON.toJSONString(jsonObject));
        HttpRequest httpRequest = new HttpRequest(urlPfx + "/socket/ws/login");
        httpRequest.setMethod(Method.POST);
        for (String s : paramsMap.keySet()) {
            httpRequest = httpRequest.form(s, paramsMap.get(s));
        }
        String resultBuffer = httpRequest.execute().body();
        log.info("resultBuffer:{}",resultBuffer);
        JSONObject response = JSON.parseObject(resultBuffer);
        if(!"0000".equals(response.get("code"))){
        }
    }

    @Override
    public void alipayuserid(JSONObject jsonObject)throws Exception  {
        Map<String, Object> paramsMap = JsonMapUtils.json2map(JSON.toJSONString(jsonObject));
        HttpRequest httpRequest = new HttpRequest(urlPfx + "/socket/ws/alipayuserid");
        httpRequest.setMethod(Method.POST);
        for (String s : paramsMap.keySet()) {
            httpRequest = httpRequest.form(s, paramsMap.get(s));
        }
        String resultBuffer = httpRequest.execute().body();
        log.info("resultBuffer:{}",resultBuffer);
        JSONObject response = JSON.parseObject(resultBuffer);
        if(!"0000".equals(response.get("code"))){
        }
    }

    @Override
    public void notifyurl(JSONObject jsonObject)throws Exception  {
        Map<String, Object> paramsMap = JsonMapUtils.json2map(JSON.toJSONString(jsonObject));
        HttpRequest httpRequest = new HttpRequest(urlPfx + "/socket/ws/notifyurl");
        httpRequest.setMethod(Method.POST);
        for (String s : paramsMap.keySet()) {
            httpRequest = httpRequest.form(s, paramsMap.get(s));
        }
        String resultBuffer = httpRequest.execute().body();
        log.info("resultBuffer:{}",resultBuffer);
        JSONObject response = JSON.parseObject(resultBuffer);
        if(!"0000".equals(response.get("code"))){
        }
    }

    @Override
    public void uploadQrCode(JSONObject jsonObject)throws Exception  {
        Map<String, Object> paramsMap = JsonMapUtils.json2map(JSON.toJSONString(jsonObject));
        HttpRequest httpRequest = new HttpRequest(urlPfx + "/socket/ws/uploadQrCode");
        httpRequest.setMethod(Method.POST);
        for (String s : paramsMap.keySet()) {
            httpRequest = httpRequest.form(s, paramsMap.get(s));
        }
        String resultBuffer = httpRequest.execute().body();
        log.info("resultBuffer:{}",resultBuffer);
        JSONObject response = JSON.parseObject(resultBuffer);
        if(!"0000".equals(response.get("code"))){
        }
    }

    @Override
    public void getTransferNo(JSONObject jsonObject)throws Exception  {
        Map<String, Object> paramsMap = JsonMapUtils.json2map(JSON.toJSONString(jsonObject));
        HttpRequest httpRequest = new HttpRequest(urlPfx + "/socket/ws/getTransferNo");
        httpRequest.setMethod(Method.POST);
        for (String s : paramsMap.keySet()) {
            httpRequest = httpRequest.form(s, paramsMap.get(s));
        }
        String resultBuffer = httpRequest.execute().body();
        log.info("resultBuffer:{}",resultBuffer);
        JSONObject response = JSON.parseObject(resultBuffer);
        if(!"0000".equals(response.get("code"))){
        }
    }

    private static Map getUrlParams(String url){
        Map<String,String> map = new HashMap<>();
        url = url.replace("?",";");
        if (!url.contains(";")){
            return map;
        }
        if (url.split(";").length > 0){
            String[] arr = url.split(";")[1].split("&");
            for (String s : arr){
                String key = s.split("=")[0];
                String value = s.split("=")[1];
                map.put(key,value);
            }
            return  map;

        }else{
            return map;
        }
    }
}
